package com.ruirui.arraylist;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

public class MyArrayList<E> extends AbstractList<E>  implements List<E>{
    int size;
    Object[] elementData;
    public MyArrayList() {
        this.elementData = new Object[10];
    }
    public MyArrayList(int initialCapacity) {
        this.elementData = new Object[initialCapacity];
        this.size = initialCapacity;
    }


    @Override
    public E get(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException();
        E elementDatum = (E) this.elementData[index];
        return elementDatum;
    }
    @Override
    public boolean add(E e) {
        int newLength = size+1;
        if (size+1 > elementData.length) {
                int length = elementData.length;
                int addLength = length + (length >> 1);
            if (addLength > size+1)
                    newLength  = addLength;
        }
       try {
           Object[] objects = Arrays.copyOf(elementData, newLength);
           objects[size++] = e;
           this.elementData = objects;
           return true;
       }catch (Exception exception){
           exception.printStackTrace();
           return false;
       }

    }
    @Override
    public E remove(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException();
        E elementDatum = (E) this.elementData[index];
        System.arraycopy(elementData, index+1, elementData, index, size-index-1);
        this.size = size-1;
        return elementDatum ;
    }
    @Override
    public int size() {
        return this.size;
    }

    public static void main(String[] args) {
        //底层 数组 默认大小10
        //三种初始化方式 1.无参初始化 直接10 ，2.容量初始化 底层需要new一个新数组 3.集合初始化 使用底层的拷贝api
        //扩容机制 ，超过数组长度限制时，扩容为原来的1.5倍 如果需求个数大于1.5倍 则按需求个数扩容

        new ArrayList<>().iterator();
    }
}
